<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文本文件差异对比</title>
    <style>
        .highlight {
            background-color: yellow;
        }
    </style>
</head>

<body>
    <h1>文本文件差异对比</h1>
    <input type="file" id="file1" accept=".txt">
    <input type="file" id="file2" accept=".txt">
    <button onclick="compareFiles()">对比文件</button>
    <div id="result"></div>

    <script>
        function compareFiles() {
            const file1Input = document.getElementById('file1');
            const file2Input = document.getElementById('file2');
            const resultDiv = document.getElementById('result');

            if (file1Input.files.length === 0 || file2Input.files.length === 0) {
                resultDiv.innerHTML = '请选择两个文本文件。';
                return;
            }

            const file1 = file1Input.files[0];
            const file2 = file2Input.files[0];

            const reader1 = new FileReader();
            const reader2 = new FileReader();

            reader1.onload = function (e1) {
                reader2.onload = function (e2) {
                    const text1 = e1.target.result;
                    const text2 = e2.target.result;

                    const diff = getDiff(text1, text2);
                    resultDiv.innerHTML = formatDiff(diff);
                };
                reader2.readAsText(file2);
            };
            reader1.readAsText(file1);
        }

        function getDiff(text1, text2) {
            const lines1 = text1.split('\n');
            const lines2 = text2.split('\n');
            const maxLength = Math.max(lines1.length, lines2.length);
            const diff = [];

            for (let i = 0; i < maxLength; i++) {
                const line1 = lines1[i] || '';
                const line2 = lines2[i] || '';

                if (line1 === line2) {
                    diff.push({ type: 'equal', line: line1 });
                } else {
                    diff.push({ type: 'diff', line1: line1, line2: line2 });
                }
            }

            return diff;
        }

        function formatDiff(diff) {
            let result = '';
            diff.forEach(item => {
                if (item.type === 'equal') {
                    result += `<p>${item.line}</p>`;
                } else {
                    result += `<p><span class="highlight">${item.line1}</span> vs <span class="highlight">${item.line2}</span></p>`;
                }
            });
            return result;
        }
    </script>
</body>

</html>
    